angular.module('starter.controllers', [])

//首页控制器
    .controller('HomeCtrl', ['$scope', '$compile', '$location', 'Category', '$ionicLoading', '$timeout',
        function ($scope, $compile, $location, Category, $ionicLoading, $timeout) {

        $scope.$root.tabstatus = 'hidetab';
        $scope.tabstatus = 'hidetab';

        //以下为题库列表处理 ---------------------------------------------------
        $scope.stores = [];
        $scope.showStoreMore = false;
        $scope.skip = 0;
        $scope.limit = 5;
            
            
        $('#_tree').delegate('p.item-text', 'click', function () {
            $('#_tree p.item-text').removeClass('active');
            $(this).addClass('active');
        })    

        //加载某题目分类下的题库
        var doLoadStore = function (node, callback) {
            if ($scope.currentNode != node) {
                $scope.stores = [];
                $scope.skip = 0;
            }
            $scope.currentNode = node;

            //显示Loading
            $ionicLoading.show({
                template: 'Loading...'
            });

            Category.getStores(node.data._id, $scope.skip, $scope.limit, function (data) {



                if (data instanceof Array) {
                    if (data.length < $scope.limit) {
                        $scope.showStoreMore = false;
                    } else {
                        $scope.showStoreMore = true;
                    }
                    $scope.skip = $scope.skip + data.length;

                    for(var i = 0; i < data.length; i++){
                        var store = data[i];
                        if(store.profession){
                            if(store.profession.indexOf(USERINFO.profession) > -1){
                                //题库适应的职业中，这个是我擅长的题目
                                store.favorite = true;
                            }
                        }
                    }
                    $scope.stores = $scope.stores.concat(data);
                    $scope.stores.sort(function(a) {
                        return a.favorite ? -1 : 1;
                    });
                }
                if (callback) {
                    callback();
                }

                //隐藏Loading;
                $timeout(function(){
                    $ionicLoading.hide()
                }, 500)
            });
        };

        //刷新题库
        $scope.refreshStore = function(){
            $scope.stores = [];
            $scope.skip = 0;
            $scope.limit = 5;

            if ($scope.currentNode) {
                doLoadStore($scope.currentNode, function () {
                    $scope.$broadcast('scroll.refreshComplete');
                });
            } else {
                $scope.$broadcast('scroll.refreshComplete');
            }
        };

        //更多题库
        $scope.moreStore = function () {
            doLoadStore($scope.currentNode);
        };

        //以下为题库分类树结构处理 ---------------------------------------------------
        //生成节点ID
        var nodeId = function () {
            return 'node_' + (new Date()).getTime() + ('' + Math.random()).substring(2);
        };

        //展开或合并节点
        var doExpandCollapse = function (node) {

            //点击节点侯即加载改分类下的题库
            doLoadStore(node);

            if (node.leaf === true) {
                return;
            }
            if (node.collapsed == true) { //当前合并，则展开
                loadChildren(node, function (node, children) {//加载子项
                    if (node.rendered == true) { //判断是否已经渲染，如果已渲染，则显示即可
                        node.collapsed = false;
                    } else {
                        //未曾渲染，将节点信息展示
                        var _id = node._id;
                        var el = $('#' + _id);
                        if (el.length > 0) {
                            var scope = node.scope ? node.scope : $scope.$new();
                            scope.node = node;
                            node.scope = scope;
                            el.closest('.item-text').after($compile(template)(scope));
                            node.rendered = true;//标记该节点已经展开并已渲染
                            node.collapsed = false; //标记该节点已经展开
                        }
                    }
                });
            } else { //当前展开，则合并
                node.collapsed = true;
            }
        };

        //加载子项，如果已经加载则不再发送异步请求
        var loadChildren = function (node, callback) {
            if (node && node.children) {
                callback(node, node.children);
            } else {

                //显示Loading
                $ionicLoading.show({
                    template: 'Loading...'
                });

                Category.getChildren(node.data._id, function (data) {

                    $ionicLoading.hide();

                    var children = [];
                    for (var idx in data) {
                        var child = {data: data[idx]};
                        child._id = nodeId();
                        child.leaf = data[idx].leaf == true;
                        child.collapsed = true;
                        child.expandCollapse = doExpandCollapse;
                        child.loadStore = doLoadStore;

                        children.push(child);
                    }
                    node.children = children;
                    callback(node, children);
                });
            }
        };

        //节点模板
        var template =
            '<ul class="list" data-ng-show="!node.collapsed" style="margin-bottom:0px;">' +
            '<li data-ng-repeat="child in node.children" class="item" style="padding-left: 10px;padding-right: 0px; padding-bottom : 0px; padding-top:0px; border: 0px;">' +
            '<p class="item-text" data-ng-click="child.expandCollapse(child)">' +
            '<i data-ng-hide="child.leaf" class="{{child.collapsed?\'ion ion-ios7-arrow-right\':\'ion ion-ios7-arrow-down\'}}"></i>' +
            '<i data-ng-show="child.leaf" style="padding-left:6px;"></i>' +
            '<i data-ng-hide="nodeicon==undefined" class="{{nodeicon}}" style="padding-left: 6px;"></i>' +
                //'<span id="{{child._id}}" class="btn btn-link btn-lg" data-ng-click="child.loadStore(child)" style="padding-left:6px;">{{child.data.text}}</span>' +
            '<span id="{{child._id}}" class="btn btn-link btn-lg" style="padding-left:6px;">{{child.data.text}}</span>' +
            '</p>'
            '</li>' +
            '</ul>';

        //内置的根节点
        $scope.node = {
            _id: nodeId(),
            data: {
                _id: 'root'
            },
            collapsed: false,
            expandCollapse: doExpandCollapse
        };

        loadChildren($scope.node, function () {
            $('#_tree').append($compile(template)($scope));
        });


        //以下为进入题库处理 ---------------------------------------------------
        $scope.joinStore = function (storeId) {
            //向服务器发送消息进入题库了
            socket.emit(Command.JOIN_STORE, {
                storeId: storeId
            });
            $location.url("/tab/store/" + storeId);
            document.getElementById('pkAudio').play(); //点击就播放音乐
        }
    }])

//题库处理逻辑
    .controller('StoreCtrl', ['$rootScope', '$scope', '$timeout', '$stateParams', '$location', 'Store', 'Battle', '$ionicLoading',
        function ($rootScope, $scope, $timeout, $stateParams, $location, Store, Battle, $ionicLoading) {

        $scope.storeId = $stateParams.storeId;
        //获取题库信息
        Store.getById($scope.storeId, function(data){
            $scope.store = data;
        });

        $scope.battles = [];
        $scope.skip = 0;
        $scope.limit = 5;
        $scope.showBattleMore = false;

        var doLoadBattles = function (callback) {

            //显示Loading
            $ionicLoading.show({
                template: 'Loading...'
            });

            Store.getBattles($scope.storeId, $scope.skip, $scope.limit, function (data) {

                //显示Loading
                $ionicLoading.hide();

                if (data instanceof Array) {
                    if (data.length < $scope.limit) {
                        $scope.showBattleMore = false;
                    } else {
                        $scope.showBattleMore = true;
                    }
                    $scope.skip = $scope.skip + data.length;
                    $scope.battles = $scope.battles.concat(data);
                }
                if (callback) {
                    callback();
                }
            });
        }

        //下拉刷新数据
        $scope.refreshBattle = function(){
            $scope.battles = [];
            $scope.skip = 0;
            $scope.limit = 5;

            doLoadBattles(function () {
                $scope.$broadcast('scroll.refreshComplete');
            });
        };

        //更多
        $scope.moreBattle = function () {
            doLoadBattles(function () {

            });
        };

        //创建一个对战
        $scope.newBattle = function () {
            Battle.newBattle($scope.storeId, function (data) {
                if (data.succ != true) {
                    function showMsg(msg, timeout, callback){
                        $scope.$root.siteMsgCls = 'active';
                        $scope.$root.siteMessage = msg;
                        $timeout(function(){
                            $scope.$root.siteMsgCls = '';
                            $scope.$root.siteMessage = '';
                            callback && callback();
                        }, timeout || 500);
                    }
                    showMsg(data.message);
                } else {
                    //跳转到对战界面
                    $location.url("/tab/battle/" + data.battle._id);
                    //向服务器发送消息开始某题库下的对战
                    socket.emit(Command.NEW_BATTLE, {
                        storeId: $scope.storeId,
                        battleId: data.battle._id
                    });
                }
            });
        };

        //进入一个练习赛
        $scope.newPractice = function () {
            Battle.newPractice($scope.storeId, function (data) {
                if (data.succ != true) {
                    //alert(data.msg);
                    function showMsg(msg, timeout, callback){
                        $scope.$root.siteMsgCls = 'active';
                        $scope.$root.siteMessage = msg;
                        $timeout(function(){
                            $scope.$root.siteMsgCls = '';
                            $scope.$root.siteMessage = '';
                            callback && callback();
                        }, timeout || 500);
                    }
                    showMsg(data.msg);
                } else {
                    //跳转到对战界面
                    $location.url("/tab/practice/" + data.practice._id);
                    //向服务器发送消息开始某题库下的练习
                    socket.emit(Command.NEW_PRACTICE, {
                        storeId: $scope.storeId,
                        practiceId: data.practice._id
                    });
                }
            });
        };

        //加入一场站对战
        $scope.joinBattle = function (battleId) {

            Battle.get(battleId, function (data) {
                if (data.status != 'N') {
                    //alert('该对战已经开始，不能再进入');
                    function showMsg(msg, timeout, callback){
                        $scope.$root.siteMsgCls = 'active';
                        $scope.$root.siteMessage = msg;
                        $timeout(function(){
                            $scope.$root.siteMsgCls = '';
                            $scope.$root.siteMessage = '';
                            callback && callback();
                        }, timeout || 500);
                    }
                    showMsg('该对战已经开始，不能再进入');
                    return;
                } else if(data.users.length >= SETTINGS.maxNum){
                    //alert('该对战参与人数已达到最大人数('+SETTINGS.maxNum+'人)，不能再加入');
                    function showMsg(msg, timeout, callback){
                        $scope.$root.siteMsgCls = 'active';
                        $scope.$root.siteMessage = msg;
                        $timeout(function(){
                            $scope.$root.siteMsgCls = '';
                            $scope.$root.siteMessage = '';
                            callback && callback();
                        }, timeout || 500);
                    }
                    showMsg('该对战参与人数已达到最大人数('+SETTINGS.maxNum+'人)，不能再加入');
                    return
                } else {
                    Battle.joinBattle(battleId, function (data) {
                        if (data.succ == true) {
                            $location.url("/tab/battle/" + battleId);
                            //向服务器发送消息进入某个对战了
                            socket.emit(Command.JOIN_BATTLE, {
                                storeId: $scope.storeId,
                                battleId: battleId
                            });
                        }else {
                            //alert(data.message);
                            function showMsg(msg, timeout, callback){
                                $scope.$root.siteMsgCls = 'active';
                                $scope.$root.siteMessage = msg;
                                $timeout(function(){
                                    $scope.$root.siteMsgCls = '';
                                    $scope.$root.siteMessage = '';
                                    callback && callback();
                                }, timeout || 500);
                            }
                            showMsg(data.message);
                        }
                    });
                }
            });
        };

        //监听到有人创建新对战, 刷新界面
        socket.on(Command.NEW_BATTLE_BROADCAST, function (data) {
            var userId = data.userId;
            var storeId = data.storeId;
            var battleId = data.battleId;

            if($scope.storeId == storeId){
                $scope.battles = [];
                $scope.skip = 0;

                doLoadBattles();
            }
        });

        //监听到对战开始, 刷新界面
        socket.on(Command.START_BATTLE_BROADCAST, function (data) {
            var userId = data.userId;
            var storeId = data.storeId;
            var battleId = data.battleId;

            if($scope.storeId == storeId){
                $scope.battles = [];
                $scope.skip = 0;

                doLoadBattles();
            }
        });

        //监听到有人加入对战
        socket.on(Command.JOIN_BATTLE_BROADCAST, function(data){
            var storeId = data.storeId;
            if($scope.storeId == storeId){
                $scope.battles = [];
                $scope.skip = 0;
                doLoadBattles();
            }
        });

        //监听到有对战结束 刷新对战列表
        socket.on(Command.STOP_BATTLE_BROADCAST, function(data){
            var storeId = data.storeId;
            if($scope.storeId == storeId){
                $scope.battles = [];
                $scope.skip = 0;
                doLoadBattles();
            }
        });

        //监听到有对战被删除，刷新对战列表
        socket.on(Command.DELETE_BATTLE_BROADCAST, function(data){
            var storeId = data.storeId;
            if($scope.storeId == storeId){
                $scope.battles = [];
                $scope.skip = 0;
                doLoadBattles();
            }
        });

        //有用户逃跑的时候刷新对战列表
        socket.on(Command.USER_FIEE_BATTLE, function (data) {
            $scope.battles = [];
            $scope.skip = 0;

            doLoadBattles();
        });

        //第一次
        doLoadBattles();

        //添加监听当进入对战列表页的时候就刷新页面
        $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
            if(toState.name == 'tab.store-detail'){
                $scope.battles = [];
                $scope.skip = 0;

                doLoadBattles();
            }
        });
    }])

//对战
    .controller('BattleCtrl', ['$rootScope', '$scope', '$state', '$stateParams', '$ionicPopup',
        '$ionicBackdrop', '$ionicActionSheet', '$ionicModal', '$timeout', '$location', '$ionicViewService', 'Battle', 'Paper', 'User',
        function ($rootScope, $scope, $state, $stateParams, $ionicPopup,
                  $ionicBackdrop, $ionicActionSheet, $ionicModal, $timeout, $location, $ionicViewService, Battle, Paper, User) {


            //是否可以开始对战
            $scope.showStartButton = false;
            //是否显示逃跑按钮
            $scope.showFleeButton = false;

            //是否显示用户信息
            $scope.showUserInfo = true;
            $scope.showText = '显示';

            //当前对战中的所有用户 答题结束后存入battle对应的user字段中
            $scope.allUsers = [];

            //记录当前对战中所有人的成绩 答题结束后存入battle的scores字段中
            $scope.allScores = {};

            //记录对战开始后逃跑的人ID, 答题结束后存入battle的fleeUsers字段中
            $scope.fleeUsers = [];

            //拖后腿道具个数
            $scope.deferPropCount = 0;

            //当连续答对5道题，则具有拖后腿道具，下面变量用户连续答对题目计数
            $scope.deferFlag = 0;

            $scope.questionNum = 0; //试卷题目数量

            //初始化数据
            $scope.battleId = $stateParams.battleId;
            Battle.get($scope.battleId, function (data) {
                //对战数据
                $scope.battle = data;
                //对战房间ID
                $scope.rid = $scope.battle.store._id + '-' + $scope.battleId;

                //倒计时, 每个题库都规定了对战的时间，用户必须在规定时间范围内打完题目
                $scope.countdown = $scope.battle.store.duration;

                //对战为尚未开始状态，并且当前用户为对战创建这则可以开始
                if ($scope.battle.status == 'N' && USERINFO.userId == $scope.battle.owner._id) {
                    $scope.showStartButton = true;
                }
                //将对战中的用户添加的总用户数中, 当前用户在点击进入该界面之前已经添加进入了，不必再添加
                $scope.allUsers = $scope.allUsers.concat($scope.battle.users);

                //如果对战已经开始或结束,回到题库界面
                if($scope.battle.status != 'N'){
                    $state.go('tab.store-detail', {storeId : $scope.battle.store._id});
                }
            });

            //设置开始基本数据变量
            var doStartBattle = function () {
                //获取试卷
                Paper.get($scope.battle.paper._id, function (data) {

                    //显示开始按钮
                    $scope.showStartButton = false;

                    //非对战创建人可以逃离战场，对战创建人不可逃离
                    //if(USERINFO.userId != $scope.battle.owner._id){
                        $scope.showFleeButton = true;
                    //}

                    //试卷
                    $scope.paper = data;


                    $scope.questionNum = $scope.paper.questions.length;

                    // I 表示正在进行
                    $scope.battle.status = 'I';

                    //记录当前用户的成绩
                    $scope.myScore = 0;
                    //记录中当前用户的选项 答题结束后存入battle的results字段中
                    $scope.myResults = [];
                    //从第一题开始做
                    $scope.currentQuestion = $scope.paper.questions.shift();
                    //记录用户对当前题目的答案
                    $scope.currentOptions = [];

                    //开启式倒计时
                    $scope.timer = setInterval(function () {
                        $scope.$apply(function(){
                            $scope.countdown = $scope.countdown - 1;
                            console.log($scope.countdown);
                            if ($scope.countdown <= 0) {
                                //对战结束
                                clearInterval($scope.timer);
                                //由对战的创建人将对战情况存入数据库，并告诉参战的其他人员对战结束
                                //参战的其他人员只需将自己的答案存入数据库即可
                                if (USERINFO.userId == $scope.battle.owner._id) {
                                    //告诉其他对战用户对战时间结束了
                                    socket.emit(Command.STOP_BATTLE, {
                                        rid: $scope.rid,
                                        userId : USERINFO.userId,
                                        storeId : $scope.battle.store._id,
                                        battleId : $scope.battleId
                                    });
                                    //将对战数据存入数据库
                                    doStopBattle(function () {});
                                }
                            }
                        });
                    }, 1000);

                    //记录没个对战人员的进度
                    $scope.allProce = {};
                    var proce = $scope.paper.questions.length;
                    for(var i = 0; i < $scope.allUsers.length;i++){
                        var user = $scope.allUsers[i];
                        $scope.allProce[user._id] = proce;
                    }
                });
            };

            //终止对战
            var doStopBattle = function (callback) {
                var allResults = {};
                allResults[USERINFO.userId] = $scope.myResults;
                Battle.ownerStop($scope.battleId, USERINFO.userId, $scope.fleeUsers,
                    $scope.allScores, allResults, function (data) {
                        $scope.battle.status = data.status;
                        if (callback) {
                            callback();
                        }
                        //如果用户答题太快已经出现了等待的提示，则先把等待提示关闭
                        if($scope.waitModel){
                            $scope.waitModel.hide();
                            $scope.waitModel.remove();
                        }
                        //显示对战结果
                        showBattleResult(data);
                    });
            };

            //对战结束显示对战结果
            var showBattleResult = function (data) {
                var cls = data.succ === true ? 'win' : 'lose';
                var template = '<ion-modal-view class="battle-end ' + cls + '">' +
                    '<ion-content>' +
                    '<div class="list card"><div class="item item-text-wrap">' + data.message +
                    '</div></div>' +
                    '<div class="list card"><div class="item item-text-wrap" ng-repeat="user in allUsers">' +
                    '<label class="label item-input"><span class="input-label text-right ">{{user.name}}：</span>' +
                    '<span ng-cloak>{{allScores[user._id] | fen}}</span></label>' +
                    '</div></div>' +
                    '<div class="button-bar">'+
                    //如果挑战成功则出现发送挑战信按钮
                    (data.succ === true ? '<a class="button button-royal post-btn" ng-click="goNewLetterBox()">发挑战信</a>' : '') +
                    '<a class="button button-royal close-btn" ng-click="closeBattleResult()">关闭</a>'+
                    '</div>'+
                    '</ion-content>' +
                    '</ion-modal-view>';

                //创建对战界面界面
                $scope.battleResult = $ionicModal.fromTemplate(template, {
                    scope: $scope,
                    animation: 'slide-in-up',
                    backdropClickToClose : false,
                    hardwareBackButtonClose : false
                });
                $scope.battleResult && $scope.battleResult.show();
            };

            //条状到发送挑战信界面
            $scope.goNewLetterBox = function(){
                console.log('发送挑战信...');
                $scope.battleResult && $scope.battleResult.hide() && $scope.battleResult.remove();
                //var url = '/tab/mybattles/newletter?storeId=' + $scope.battle.store._id;
                //$location.url(url);
                $state.go('tab.mybattles-newletter-storeId', {storeId : $scope.battle.store._id});
            };

            //关闭对战结果界面
            $scope.closeBattleResult = function() {
                console.log('关闭对战结果显示界面');
                $scope.battleResult && $scope.battleResult.hide() && $scope.battleResult.remove();
                //回到题库界面
                $state.go('tab.store-detail', {storeId : $scope.battle.store._id});
            };

            //销毁该对象
            $scope.$on('$destroy', function() {
                console.log('battle destroy');
                clearInterval($scope.timer);
                $scope.battleResult && $scope.battleResult.hide() && $scope.battleResult.remove();
                $scope.deferModel && $scope.deferModel.hide() && $scope.deferModel.remove();
                $scope.waitModel && $scope.waitModel.remove();
                $scope.messageModel && $scope.messageModel.remove();
            });

            $scope.battleStatus = false; //对战状态, false 准备阶段,  true 进行中

            //开始对战
            $scope.startBattle = function () {
                //判断是否够最少对战人数
                var num = $scope.allUsers.length;
                if(num < SETTINGS.minNum){
                    var template = '<div class="list card"><div class="item item-text-wrap">当前进入战场的只有'
                        + num +'人,低于最少对战人数' + SETTINGS.minNum + ',不能开始,请稍等</div></div>';
                    $scope.messageModel = $ionicModal.fromTemplate(template);
                    $scope.messageModel.show();
                    $timeout(function(){
                        $scope.messageModel && $scope.messageModel.hide() && $scope.messageModel.remove();
                    }, 1000);
                    return;
                }

                $scope.battleStatus = true;

                //告诉其他对战用户开始对战
                socket.emit(Command.READY_BATTLE, {
                    rid: $scope.rid
                });

                $timeout(function () {
                    $scope.battleStatus = false;
                    Battle.start($scope.battleId, function (data) {
                        //告诉其他对战用户开始对战
                        socket.emit(Command.START_BATTLE, {
                            rid: $scope.rid,
                            storeId : $scope.battle.store._id,
                            battleId : $scope.battleId
                        });
                        //开始，设置一些基本数据
                        doStartBattle();
                    });
                }, 3000);
            };

            //选择一个选项
            $scope.doCheckOpt = function (opt, event) {
                var idx = opt.idx;
                if (event.target && event.target.checked) {//选中
                    $scope.currentOptions.push(idx);
                } else {//取消选中
                    var t = $scope.currentOptions.indexOf(idx);
                    if (t >= 0) {//已经选过了,从中删除之前选的
                        $scope.currentOptions.splice(t, 1);
                    }
                }
            };


            function showMsg(msg, timeout, callback){
                $scope.$root.siteMsgCls = 'active';
                $scope.$root.siteMessage = msg;
                $timeout(function(){
                    $scope.$root.siteMsgCls = '';
                    $scope.$root.siteMessage = '';
                    callback && callback();
                }, timeout || 500);
            }

            //提交答案
            $scope.doCommit = function () {
                var answer = $scope.currentQuestion.answer;
                var options = $scope.currentOptions;

                if (options.length <= 0) {
                    /*var template = '<div class="list card"><div class="item item-text-wrap">你还没有选择答案~</div></div>';
                    $scope.messageModel = $ionicModal.fromTemplate(template);
                    $scope.messageModel.show();
                    $timeout(function(){
                        $scope.messageModel && $scope.messageModel.hide() && $scope.messageModel.remove();
                    }, 300);
                    return;*/
                    showMsg('你还没有选择答案');
                    return;
                }

                //记录我的答题选项
                $scope.myResults.push({
                    questions: $scope.currentQuestion._id,
                    opts: options
                });


                //判断如果答案完全正确，则算对，
                var a = answer.sort().join();
                var r = options.sort().join();
                var message = '<span class="answer">正确答案是:' + a + '</span>';
                if (a == r) { //答对了
                    message += ' <span class="answer-right">恭喜你，答对了~</span>';
                    //连续答对题目计数加1，当连续答对5到题目的时候，道具数加1
                    $scope.deferFlag++;
                    if($scope.deferFlag == 5){
                        //if($scope.allUsers.length >= 2){
                            $scope.deferPropCount++;
                        //}
                        $scope.deferFlag = 0;
                    }
                    //记录用户得分
                    $scope.myScore += ($scope.currentQuestion.score || 1); //至少也得1分
                    //记录自己的成绩
                    $scope.allScores[USERINFO.userId] = $scope.myScore;

                } else { //答错了
                    //将拖后退道具计数置为0
                    $scope.deferFlag == 0;
                    message += ' <span class="answer-wrong">呃，答错了~</span>';
                }

                //继续下一题
                var question = $scope.paper.questions.shift();
                var proce = $scope.paper.questions.length;
                //记录自己还剩多少题
                $scope.allProce[USERINFO.userId] = proce;
                //向其他用户广播该用户的得分情况，在其他对手那里记录成绩
                socket.emit(Command.BATTLE_NEWS, {
                    rid: $scope.rid,
                    userId : USERINFO.userId,
                    score: $scope.myScore,
                    proce: proce
                });

                //提示
                var template = '<div class="list card"><div class="item item-text-wrap">'
                    + message+ '</div></div>';
                $scope.messageModel = $ionicModal.fromTemplate(template);
                $scope.messageModel.show();
                $timeout(function(){
                    $scope.messageModel && $scope.messageModel.hide() && $scope.messageModel.remove();
                    if (question) {
                        $scope.currentQuestion = question;
                        $scope.currentOptions = [];
                    } else {
                        var flag = true; //表示所有人都打完了
                        for(var uid in $scope.allProce){
                            if($scope.allProce[uid] > 0){
                                flag = false;
                                break;
                            }
                        }
                        if(flag == true){//所有人都打完题了
                            clearInterval($scope.timer);
                            //由对战的创建人将对战情况存入数据库，并告诉参战的其他人员对战结束
                            //参战的其他人员只需将自己的答案存入数据库即可
                            if (USERINFO.userId == $scope.battle.owner._id) {
                                //告诉其他对战用户对战时间结束了
                                socket.emit(Command.STOP_BATTLE, {
                                    rid: $scope.rid
                                });
                                //将对战数据存入数据库
                                doStopBattle(function () {});
                            }else {
                                doUserStopBattle();
                            }
                        }else { //有人还没有完成答题
                            if($scope.countdown <= 0){ //已经到时间了
                                clearInterval($scope.timer);
                                $timeout(function(){
                                    if(USERINFO.userId != $scope.battle.owner._id){
                                        doUserStopBattle();
                                    }else {
                                        //告诉其他对战用户对战时间结束了
                                        socket.emit(Command.STOP_BATTLE, {
                                            rid: $scope.rid
                                        });
                                        //将对战数据存入数据库
                                        doStopBattle(function () {});
                                    }
                                }, 1000);
                            }else {
                                showWaitPopup();
                            }
                        }
                    }
                }, 300);
            };

            //开始
            var showWaitPopup = function(){

                var template = '<div class="list card">' +
                    '<div class="item item-text-wrap">' +
                    '<span>您真是太厉害了，已经没题了，距对战结束还需{{countdown}}秒</span>' +
                    '</div>' +
                    '</div>';
                $scope.waitModel = $ionicModal.fromTemplate(template, {
                    scope: $scope,
                    animation: 'slide-in-up',
                    backdropClickToClose : false,
                    hardwareBackButtonClose : false
                });
                $scope.waitModel.show();
            };

            //逃跑
            var doFleeBattle = function (callback) {

                var template = '<div class="list card"><div class="item item-text-wrap">您确定要逃离吗?</div></div>';
                if(USERINFO.userId != $scope.battle.owner._id){
                    template = '<div class="list card"><div class="item item-text-wrap">请您不要离开!</div></div>';
                }
                var fleePopup = $ionicPopup.show({
                    title: '提示',
                    template: template,
                    scope: $scope,
                    buttons : [{
                        text: '<b>不玩儿了~</b>',
                        type: 'button-positive',
                        onTap: function (e) {
                            fleePopup.close();

                            //关闭等待提示
                            if($scope.waitModel){
                                $scope.waitModel.hide();
                                $scope.waitModel.remove();
                            }
                            if($scope.timer){
                                clearInterval($scope.timer);
                            }
                            //记录逃离用户ID
                            $scope.fleeUsers.push(USERINFO.userId);

                            //执行回调方法
                            if(callback){
                                callback();
                            }
                        }
                    }, {
                        text: '<b>再玩会儿吧~</b>',
                        type: 'button-yoral',
                        onTap: function (e) {
                            fleePopup.close();
                            e.preventDefault();
                        }
                    }]
                });
            };

            //退出挑战
            $scope.fleeBattle = function(){
                doFleeBattle(function(){
                    //告诉其他对战人员该用户已经逃离
                    socket.emit(Command.USER_FIEE_BATTLE, {
                        userId: USERINFO.userId,
                        userName : USERINFO.name,
                        rid: $scope.rid
                    });
                    //回到题库界面
                    $state.go('tab.store-detail', {storeId : $scope.battle.store._id});
                });
            }

            //是否显示用户信息
            $scope.showInfo = function(){
                $scope.showUserInfo = !$scope.showUserInfo;
                var show = $scope.showUserInfo;
                if(show){
                    $scope.showText = '隐藏';
                } else {
                    $scope.showText = '显示';
                }
            }

            //有用户加入了对战, 将当前用户放入到用户集中
            socket.on(Command.USER_JOIN_BATTLE, function (data) {
                console.log(data);
                $scope.$apply(function(){
                    if(data.battleId == $scope.battleId){
                        //如果已经加入则不需在加入
                        for (var i = 0, len = $scope.allUsers.length; i < len; i++) {
                            var u = $scope.allUsers[i];
                            if (u._id == data.userId) {
                                return;
                            }
                        }
                        //没加入的话则获取用户数据加入进来
                        User.get(data.userId, function (data) {
                            $scope.allUsers.push(data);
                        });
                    }
                });
            });

            //非对战创建者，监听到对战创建人发送来的对战开始消息
            socket.on(Command.START_BATTLE, function (data) {
                $scope.$apply(function(){
                    var battleId = data.battleId;
                    if($scope.battleId == battleId){
                        doStartBattle();
                    }
                });
            });

            socket.on(Command.READY_BATTLE, function () {
                $scope.$apply(function(){
                    $scope.battleStatus = true;
                });
            });

            //接收到其他用户的战报,更新其他人的成绩表
            socket.on(Command.BATTLE_NEWS, function (data) {
                $scope.$apply(function(){
                    var userId = data.userId;
                    var score = data.score;
                    var proce = data.proce;
                    $scope.allScores[userId] = score;
                    $scope.allProce[userId] = proce;
                });
            });

            //得知有人逃离，则将其ID记录下来
            socket.on(Command.USER_FIEE_BATTLE, function (data) {
                $scope.$apply(function(){
                    var userId = data.userId;
                    var userName = data.userName;
                    $scope.fleeUsers.push(userId);
                    //提示
                    var template = '<div class="list card"><div class="item item-text-wrap">用户:'
                        + userName + ' 逃跑了</div></div>';
                    $scope.messageModel = $ionicModal.fromTemplate(template);
                    $scope.messageModel.show();
                    $timeout(function(){
                        $scope.messageModel && $scope.messageModel.hide() && $scope.messageModel.remove();
                        //当用户掉线或逃跑之后不在泳道里显示这个用户
                        for(var i = 0;i < $scope.allUsers.length; i++){
                            var u = $scope.allUsers[i];
                            if(u._id == userId){
                                $scope.allUsers.splice(i, 1);
                            }
                        }
                    }, 300);
                });
            });

            /**
             * 完成对战
             */
            var doUserStopBattle = function(){
                var userResults = {};
                userResults[USERINFO.userId] = $scope.userResults;
                Battle.userStop($scope.battleId, USERINFO.userId, $scope.myScore, userResults, function (data) {
                    $scope.battle.status = data.status;

                    //关闭等待提示
                    $scope.waitModel && $scope.waitModel.hide() && $scope.waitModel.remove();
                    $scope.battleResult && $scope.battleResult.hide() && $scope.battleResult.remove();
                    $scope.deferModel && $scope.deferModel.hide() && $scope.deferModel.remove();
                    $scope.messageModel && $scope.messageModel.hide() && $scope.messageModel.remove();

                    //显示对战结果
                    showBattleResult(data);
                });
            };

            //接收到对战结束的消息
            socket.on(Command.STOP_BATTLE, function (d) {
                console.log('stop battle ' + d.userId + ' ' + (new Date()).getTime());
                $scope.$apply(function(){
                    if(USERINFO.userId != $scope.battle.owner._id){
                        if($scope.timer){
                            clearInterval($scope.timer);
                        }
                        doUserStopBattle();
                    }
                });
            });

            //延迟某人答题
            //不是自己、有拖后腿道具、并且被拖后腿的人还没完成答题
            $scope.deferUser = function(userId){
                if(userId != USERINFO.userId
                    && $scope.deferPropCount > 0
                    && $scope.allProce[userId] > 0){
                    $ionicActionSheet.show({
                        titleText: '您有' + $scope.deferPropCount + '个延迟道具可以用~',
                        destructiveText: '让他延时3秒~',
                        cancelText: '放他一马',
                        cancel: function () {
                            console.log('取消使用道具....');
                        },
                        destructiveButtonClicked: function () {
                            console.log('使用道具....');
                            //应用道具后将道具数减一
                            if($scope.deferPropCount > 0){
                                $scope.deferPropCount--;
                            }else {
                                $scope.deferPropCount = 0;
                            }
                            console.log('道具数' + $scope.deferPropCount);

                            //$scope.deferFlag = 0;
                            //发送应用道具命令
                            socket.emit(Command.DEFER_USER, {
                                rid : $scope.rid,
                                userId : USERINFO.userId,
                                userName : USERINFO.name,
                                toUser : userId
                            });
                            return true;
                        }
                    });
                }
            };

            //监听到有人对自己使用了拖延道具
            socket.on(Command.DEFER_USER, function(data){
                $scope.$apply(function(){
                    var toUser = data.toUser;
                    var userId = data.userId;
                    var userName = data.userName;
                    if(toUser == USERINFO.userId){
                        var template = '<div class="list card"><div class="item item-text-wrap">你被'
                            + userName + '使用了延迟3秒道具</div></div>';
                        $scope.deferModel = $ionicModal.fromTemplate(template, {
                            scope: $scope,
                            animation: 'slide-in-up',
                            backdropClickToClose : false,
                            hardwareBackButtonClose : false
                        });
                        $scope.deferModel.show();
                        $timeout(function(){
                            $scope.deferModel && $scope.deferModel.hide() && $scope.deferModel.remove();
                            $ionicBackdrop.retain();
                            $timeout(function () {
                                $ionicBackdrop.release();
                            }, 2000);
                        }, 1000);
                    }
                });
            });

            //对战创建人逃离对战
            socket.on(Command.OWNER_FLEE_BATTLE, function(d){
                $scope.$apply(function(){
                    var template = '<div class="list card"><div class="item item-text-wrap">对战创建人逃离了这个对战，所以只好下次再战了~</div></div>';
                    $scope.messageModel = $ionicModal.fromTemplate(template);
                    $scope.messageModel.show();
                    $timeout(function(){
                        $scope.messageModel && $scope.messageModel.hide() && $scope.messageModel.remove();

                        //修改对战状态
                        $scope.battle.status = 'F';

                        $timeout(function(){
                            //回到题库界面
                            $state.go('tab.store-detail', {storeId : $scope.battle.store._id});
                        }, 500);

                    }, 1000);
                });
            });

            //监听当用户点击返回按钮的时候，如果只有一个人(自己)，则可以退出改对战
            $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
                //当用户加入某对战的时候,则不能通过点击返回按钮退出对战，必须点击界面中的退出
                if(fromState.name == 'tab.battle-detail'){
                    if($scope.battle){
                        var isOwner = (USERINFO.userId == $scope.battle.owner._id); //是否为对战创建人
                        var status = $scope.battle.status; //对战状态
                        //var us = $scope.allUsers.length; //用户数
                        if(isOwner){//自己创建的对战
                            if(status == 'N'){
                                //结束对战
                                event.preventDefault();
                                /*
                                Battle.ownerStop($scope.battleId, USERINFO.userId, [USERINFO.userId], {}, {}, function(data){
                                    //发送消息其他人也退出对战
                                    socket.emit(Command.OWNER_FLEE_BATTLE, {
                                        rid: $scope.rid
                                    });
                                    //修改对战状态
                                    $scope.battle.status = 'F';
                                    //回到题库界面
                                    $state.go('tab.store-detail', {storeId : $scope.battle.store._id});
                                });
                                */
                                Battle.delete($scope.battleId, function(data){
                                    //发送消息其他人也退出对战
                                    socket.emit(Command.DELETE_BATTLE, {
                                        rid: $scope.rid,
                                        userId : USERINFO.userId,
                                        storeId : $scope.battle.store._id,
                                        battleId : $scope.battleId
                                    });
                                    $scope.battle.status = 'F';
                                    //回到题库界面
                                    $state.go('tab.store-detail', {storeId : $scope.battle.store._id});
                                });
                            }else if(status == 'I'){
                                event.preventDefault();
                                //正在对战的时候,对战创建人逃跑,则终止对战
                                Battle.ownerStop($scope.battleId, USERINFO.userId, [USERINFO.userId], {}, {}, function(data){
                                    //发送消息其他人也退出对战
                                    socket.emit(Command.OWNER_FLEE_BATTLE, {
                                        rid: $scope.rid,
                                        userId : USERINFO.userId,
                                        storeId : $scope.battle.store._id,
                                        battleId : $scope.battleId
                                    });
                                    //修改对战状态
                                    $scope.battle.status = 'F';
                                    //回到题库界面
                                    $state.go('tab.store-detail', {storeId : $scope.battle.store._id});
                                });
                            }else if(status == 'F'){
                                //对战已经结束，点击返回按钮就无所谓了
                            }
                        }else {//别人创建的对战
                            if(status == 'N' || status == 'I'){
                                //关闭等待提示
                                if($scope.waitModel){
                                    $scope.waitModel.hide();
                                    $scope.waitModel.remove();
                                }
                                if($scope.timer){
                                    clearInterval($scope.timer);
                                }
                                //记录逃离用户ID
                                $scope.fleeUsers.push(USERINFO.userId);
                                //$scope.myStatus = 'F';//我已经跑了
                                //告诉其他对战人员该用户已经逃离
                                socket.emit(Command.USER_FIEE_BATTLE, {
                                    userId: USERINFO.userId,
                                    userName : USERINFO.name,
                                    rid: $scope.rid
                                });
                                /*
                                if($scope.fleeUsers && $scope.fleeUsers.indexOf(USERINFO.userId) < 0){//当前用户没有逃跑
                                    event.preventDefault();
                                    doFleeBattle(function(){
                                        $scope.myStatus = 'F';//我已经跑了
                                        //告诉其他对战人员该用户已经逃离
                                        socket.emit(Command.USER_FIEE_BATTLE, {
                                            userId: USERINFO.userId,
                                            rid: $scope.rid
                                        });
                                        //回到题库界面
                                        $state.go('tab.store-detail', {storeId : $scope.battle.store._id});
                                    });
                                }
                                */
                            }else {

                            }
                        }
                    }
                }
            });
        }])

//练习
    .controller('PracticeCtrl', ['$scope', '$stateParams', '$ionicPopup', '$location', '$ionicViewService', '$ionicModal', 'Battle', 'Practice', 'Paper', '$timeout',
        function ($scope, $stateParams, $ionicPopup, $location, $ionicViewService, $ionicModal, Battle, Practice, Paper, $timeout) {

            //start practice
            var doStartButton = function () {
                Practice.start($scope.practiceId, function (data) {
                    //状态
                    $scope.practice.status = data.status;
                    //获取试卷
                    Paper.get($scope.practice.paper._id, function (data) {

                        //显示开始按钮
                        $scope.showStartButton = false;

                        //试卷
                        $scope.paper = data;

                        //记录当前用户的成绩
                        $scope.myScore = 0;

                        //记录中当前用户的选项 答题结束后存入battle的results字段中
                        $scope.myResults = [];

                        //从第一题开始做
                        $scope.currentQuestion = $scope.paper.questions.shift();

                        //创建做过的题目数据
                        $scope.doPapers = [];

                        //记录用户对当前题目的答案
                        $scope.currentOptions = [];
                    });
                });
            };

            //初始化数据
            $scope.practiceId = $stateParams.practiceId;
            Practice.get($scope.practiceId, function (data) {
                //练习数据
                $scope.practice = data;

                //当前练习人
                $scope.user = data.user;

                //开始练习
                doStartButton();
            });

            //选择一个选项
            $scope.doCheckOpt = function (opt, event) {
                var idx = opt.idx;
                if (event.target && event.target.checked) {//选中
                    $scope.currentOptions.push(idx);
                } else {//取消选中
                    var t = $scope.currentOptions.indexOf(idx);
                    if (t >= 0) {//已经选过了,从中删除之前选的
                        $scope.currentOptions.splice(t, 1);
                    }
                }
            };

            //对战结束显示对战结果
            var showPracticeResult = function (data) {

                var template =
                    '<div class="list card">' +
                    '<div class="item item-text-wrap">' +
                    '<label class="label item-input"><span class="input-label text-right ">{{user.name}}</span>' +
                    '<span ng-cloak>{{myScore | fen}}</span></label>' +
                    '</div>' +
                    '</div>';

                var myPopup = $ionicPopup.show({
                    template: template,
                    title: '练习结果',
                    subTitle: data.message,
                    scope: $scope,
                    buttons: [{
                        text: '再来一次',
                        type: 'button-royal',
                        onTap: function (e) {
                            myPopup.close();
                            Battle.newPractice($scope.practice.store._id, function (data) {
                                if (data.succ != true) {
                                    //alert(data.msg);
                                } else {
                                    var practice = data.practice;
                                    $scope.practiceId = practice._id;
                                    Practice.get($scope.practiceId, function (data) {
                                        //练习数据
                                        $scope.practice = data;
                                        //当前练习人
                                        $scope.user = data.user;

                                        //开始练习
                                        doStartButton();

                                        //广播新建练习消息
                                        socket.emit(Command.NEW_PRACTICE, {
                                            storeId: $scope.practice.store._id,
                                            practiceId: $scope.practice._id
                                        });
                                    });
                                }
                            });
                        }
                    }, {
                        text: '<b>关闭</b>',
                        type: 'button-positive',
                        onTap: function (e) {
                            myPopup.close();
                            var backView = $ionicViewService.getBackView();
                            backView && backView.go();
                        }
                    }]
                });
            };

            //练习结束
            var doStopPractice = function (callback) {
                Practice.stop($scope.practiceId, USERINFO.userId, $scope.myScore, $scope.myResults, function (data) {
                    $scope.practice.status = data.status;
                    if (callback) {
                        callback();
                    }
                    //显示练习结果
                    showPracticeResult(data);
                });
            };

            /**
             * 返回上一题
             */
            $scope.returnPrev = function () {
                $scope.paper.questions.unshift($scope.currentQuestion);
                $scope.currentQuestion = $scope.doPapers.pop();
                $scope.currentOptions = [];
            }

            //提交答案
            $scope.doCommit = function () {
                var answer = $scope.currentQuestion.answer;
                var options = $scope.currentOptions;

                if (options.length <= 0) {
                    var template = '<div class="list card"><div class="item item-text-wrap">你还没选答案~</div></div>';
                    $scope.messageModel = $ionicModal.fromTemplate(template);
                    $scope.messageModel.show();
                    $timeout(function(){
                        $scope.messageModel && $scope.messageModel.hide() && $scope.messageModel.remove();
                    }, 300);
                    return;
                }

                //记录我的答题选项
                $scope.myResults.push({
                    questions: $scope.currentQuestion._id,
                    opts: options
                });

                //判断如过所选的答案完全正确则认为正确
                var a = answer.sort().join();
                var r = options.sort().join();

                /*//判断如果该题的正确答案都包含在用户所选的答案中则认为该题答对了
                //例如：如果答案是A，选择了ABC等多个时，依然显示该题做对了
                var r = 0;
                var a = answer.length;
                answer.forEach(function(t){
                    if(options.indexOf(t) > -1){
                        r++;
                    }
                });*/

                var message = '<span class="answer">正确答案是:' + (answer.sort().join()) + '</span>';
                if (a === r) { //答对了
                    //记录用户得分
                    $scope.myScore += ($scope.currentQuestion.score || 1); //至少也得1分
                    message += ' <span class="answer-right">恭喜你，答对了~</span>';
                } else { //打错了
                    message += ' <span class="answer-wrong">呃，答错了~</span>';
                }

                //提示
                var template = '<div class="list card"><div class="item item-text-wrap">'
                    + message+ '</div></div>';
                $scope.messageModel = $ionicModal.fromTemplate(template);
                $scope.messageModel.show();
                $timeout(function(){
                    $scope.messageModel && $scope.messageModel.hide() && $scope.messageModel.remove();

                    //继续下一题
                    var question = $scope.paper.questions.shift();
                    if (question) {
                        $scope.doPapers.push($scope.currentQuestion); //已经做过的题目
                        $scope.currentQuestion = question;
                        $scope.currentOptions = [];
                    } else {
                        //题目完了
                        doStopPractice();
                    }
                }, 300);
            };

        }])

//我的挑战
    .controller('MyBattlesCtrl', ['$scope', '$timeout', '$location', 'Store', 'Battle', 'Letter',
        function ($scope, $timeout, $location, Store, Battle, Letter) {

        //以下为我参与的对战处理 ------------------------------------------------
        $scope.battles = [];
        $scope.skip = 0;
        $scope.limit = 5;
        $scope.showBattleMore = false;

        var doLoadBattles = function (callback) {
            Store.getMyBattles($scope.skip, $scope.limit, function (data) {
                if (data instanceof Array) {
                    if (data.length < $scope.limit) {
                        $scope.showBattleMore = false;
                    } else {
                        $scope.showBattleMore = true;
                    }
                    $scope.skip = $scope.skip + data.length;
                    $scope.battles = $scope.battles.concat(data);

                    if (callback) {
                        callback();
                    }
                }
            });
        }

        $scope.moreBattle = function () {
            doLoadBattles(function () {
                $scope.$broadcast('scroll.refreshComplete');
                //$scope.$apply();
            });
        };

        doLoadBattles();

        //以下为收件箱处理 ------------------------------------------------
        $scope.inboxLetters = [];
        $scope.inboxSkip = 0;
        $scope.inboxLimit = 5;
        $scope.inboxShowMore = false;

        var doLoadInboxLetters = function (callback) {
            Letter.getInbox($scope.inboxSkip, $scope.inboxLimit, function (data) {
                if (data instanceof Array) {
                    if (data.length < $scope.inboxLimit) {
                        $scope.inboxShowMore = false;
                    } else {
                        $scope.inboxShowMore = true;
                    }
                    $scope.inboxSkip = $scope.inboxSkip + data.length;
                    $scope.inboxLetters = $scope.inboxLetters.concat(data);
                }
                if (callback) {
                    callback();
                }
            });
        }

        $scope.moreInbox = function () {
            doLoadInboxLetters(function () {
                $scope.$broadcast('scroll.refreshComplete');
            });
        }

        doLoadInboxLetters();

        //以下为发件箱处理 ------------------------------------------------
        $scope.outboxLetters = [];
        $scope.outboxSkip = 0;
        $scope.outboxLimit = 5;
        $scope.outboxShowMore = false;

        var doLoadOutboxLetters = function (callback) {
            Letter.getOutbox($scope.outboxSkip, $scope.outboxLimit, function (data) {
                if (data instanceof Array) {
                    if (data.length < $scope.outboxLimit) {
                        $scope.outboxShowMore = false;
                    } else {
                        $scope.outboxShowMore = true;
                    }
                    $scope.outboxSkip = $scope.outboxSkip + data.length;
                    $scope.outboxLetters = $scope.outboxLetters.concat(data);
                }
                if (callback) {
                    callback();
                }
            });
        }

        $scope.moreOutbox = function () {
            doLoadOutboxLetters(function () {
                $scope.$broadcast('scroll.refreshComplete');
            });
        }

        doLoadOutboxLetters();

        //以下为进入题库处理 ---------------------------------------------------
        $scope.joinBattle = function (storeId, letterId) {
            //向服务器发送消息进入题库了
            socket.emit(Command.JOIN_STORE, {
                storeId: storeId
            });

            Battle.newBattle(storeId, function (data) {
                if (data.succ != true) {
                    function showMsg(msg, timeout, callback){
                        $scope.$root.siteMsgCls = 'active';
                        $scope.$root.siteMessage = msg;
                        $timeout(function(){
                            $scope.$root.siteMsgCls = '';
                            $scope.$root.siteMessage = '';
                            callback && callback();
                        }, timeout || 500);
                    }
                    showMsg(data.message);
                    //alert(data.message);
                } else {
                    //跳转到对战界面
                    $location.url("/tab/battle/" + data.battle._id);
                    //向服务器发送消息开始某题库下的对战
                    socket.emit(Command.NEW_BATTLE, {
                        storeId: $scope.storeId,
                        battleId: data.battle._id
                    });
                }
                //先删除应战记录
                $scope.deleteLetter(letterId);
            });
        }

        //删除收件内容
        $scope.deleteLetter = function(letterId){
            Letter.delete(letterId, function(data){

                console.log(data);

                $scope.inboxLetters = [];
                $scope.inboxSkip = 0;
                $scope.inboxLimit = 5;
                $scope.inboxShowMore = false;
                doLoadInboxLetters();

                $scope.outboxLetters = [];
                $scope.outboxSkip = 0;
                $scope.outboxLimit = 5;
                $scope.outboxShowMore = false;
                doLoadOutboxLetters();
            });
        }
    }])

//发送信件
    .controller('NewLetterCtrl', ['$scope', '$timeout', '$ionicViewService', '$stateParams', 'Letter', '$location',
        function ($scope, $timeout, $ionicViewService, $stateParams, Letter, $location) {

        /*
        var params = $location.$$url.substring(25);
        if(params && params.length > 8){
            var params = params.split('=');
            if(params.length >= 2 && params[0] == 'storeId'){
              $scope.storeId = params[1];
            }
        }
        */

        if($stateParams.storeId){
            $scope.storeId = $stateParams.storeId;
        }

        $scope.showQueryResult = false;
        //查询内容
        $scope.query = {
            name : '',
            result : []
        };
        //信内容
        $scope.letter = {
            text : '快来打破我的最高纪录吧~'
        };
        //收信人数组
        $scope.receivers = [];

        $scope.doQeury = function(){
            var name = $scope.query.name;
            if(name && name.length >= 1){
                Letter.queryUser(name, function(data){
                    if(data && data.length > 0){
                        $scope.query.result = data;
                        $scope.showQueryResult = true;
                    }else {
                        $scope.query.result = [];
                        $scope.showQueryResult = false;
                    }
                });
            }else{
                $scope.query.result = [];
            }
        };

        //选择一个用户
        $scope.doCheckUser = function(user){
            //检查是否已经添加
            for(var i = 0, len = $scope.receivers.length; i < len; i++){
                var temp = $scope.receivers[i];
                if(temp._id == user._id){
                    return;
                }
            }
            $scope.receivers.push(user);
            $scope.showQueryResult = false;
        };

        //取消某人
        $scope.doUnCheckUser = function(user){
            for(var i = 0, len = $scope.receivers.length; i < len; i++){
                var temp = $scope.receivers[i];
                if(temp._id == user._id){
                   $scope.receivers.splice(i,1);i++;
                };
            }
        };

        //发送信息
        $scope.sendLetter = function () {
            if($scope.receivers.length < 1){
                //alert('你没有选定挑战人');
                function showMsg(msg, timeout, callback){
                    $scope.$root.siteMsgCls = 'active';
                    $scope.$root.siteMessage = msg;
                    $timeout(function(){
                        $scope.$root.siteMsgCls = '';
                        $scope.$root.siteMessage = '';
                        callback && callback();
                    }, timeout || 500);
                }
                showMsg('你没有选定挑战人');
                return;
            }
            var text = $scope.letter.text;
            if(!text || text.length == 0){
                //alert('您还没输入内容');
                function showMsg(msg, timeout, callback){
                    $scope.$root.siteMsgCls = 'active';
                    $scope.$root.siteMessage = msg;
                    $timeout(function(){
                        $scope.$root.siteMsgCls = '';
                        $scope.$root.siteMessage = '';
                        callback && callback();
                    }, timeout || 500);
                }
                showMsg('您还没输入内容');
                return;
            }
            var recs = [];
            for(var i = 0, len = $scope.receivers.length; i< len; i++){
                recs.push($scope.receivers[i]._id);
            }
            Letter.send(USERINFO.userId, $scope.storeId, recs, text, function(data){
                //var backView = $ionicViewService.getBackView();
                //backView && backView.go();

                $location.url('/tab/mybattles')
            });
        }
    }])

//荣誉榜
    .controller('HonorCtrl', ['$scope', 'Honor',
        function ($scope, Honor) {

        $scope.users = [];
        $scope.skip = 0;
        $scope.limit = 5;
        $scope.showUserMore = false;

        var doLoadUsers = function (callback) {
            Honor.get($scope.skip, $scope.limit, function (data) {
                if (data instanceof Array) {
                    if (data.length < $scope.limit) {
                        $scope.showUserMore = false;
                    } else {
                        $scope.showUserMore = true;
                    }
                    $scope.skip = $scope.skip + data.length;
                    $scope.users = $scope.users.concat(data);
                }
                if (callback) {
                    callback();
                }
            });
        }

        $scope.moreUser = function () {
            doLoadUsers(function () {
                $scope.$broadcast('scroll.refreshComplete');
            });
        };

        doLoadUsers();
    }])

//其他设置
    .controller('OtherCtrl', ['$rootScope', '$scope', '$stateParams', '$ionicModal', 'User',
        function ($rootScope, $scope, $stateParams, $ionicModal, User) {

        //加载用户信息
        User.get(USERINFO.userId, function(data){
            $scope.user = data;
        });

        //添加监听当进入页面的时候刷新用户数据
        $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
            if(toState.name == 'tab.other'){
                User.get(USERINFO.userId, function(data){
                    $scope.user = data;
                });
            }
        });

        $scope.photos = ['user1', 'user2', 'user3', 'user4', 'user5'];

        //修改头像
        $scope.changePhoto = function(){
            if(!$scope.allPhotos){
                var template = '<ion-modal-view><ion-content>'
                    + '<div class="bar bar-header" style="height: 40px;"><div class="title"  style="color: #fff;">可选头像</div>'
                    + '<a class="button button-clear close-btn" ng-click="cancelChange()">关闭</a>'
                    +'</div>'
                    + '<div class="photo-album"><ul><li ng-repeat="p in photos" ng-click="selectPhoto(p)"><img ng-src="/images/{{p}}.png"></li></ul></div>'
                    + '</ion-content></ion-modal-view>';
                //创建对战界面界面
                $scope.allPhotos = $ionicModal.fromTemplate(template, {
                    scope: $scope,
                    animation: 'slide-in-up',
                    backdropClickToClose : false,
                    hardwareBackButtonClose : false
                });
            }
            $scope.allPhotos.show();
        };

        $scope.cancelChange = function(){
            $scope.allPhotos.hide();
        };

        //选中一个图片
        $scope.selectPhoto = function(photo){
            $scope.allPhotos.hide();
            User.setPhoto($scope.user._id, photo, function(data){
                console.log(data);
                $scope.user.photo = photo;
            });
        }
    }]);


